extends Node2D

@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var balance: Sprite2D = $Balance
@onready var coins: Array[Coin] = [$CoinContainer/Coin1, $CoinContainer/Coin2, $CoinContainer/Coin3, $CoinContainer/Coin4, $CoinContainer/Coin5, $CoinContainer/Coin6, $CoinContainer/Coin7, $CoinContainer/Coin8, $CoinContainer/Coin9, $CoinContainer/Coin10, $CoinContainer/Coin11, $CoinContainer/Coin12]
@onready var first: Button = $HistoryContainer/First
@onready var second: Button = $HistoryContainer/Second
@onready var third: Button = $HistoryContainer/Third
@onready var contestant_mode: Button = $ModeContainer/ContestantMode
@onready var quizmaster_mode: Button = $ModeContainer/QuizmasterMode
@onready var left_weigh_coins: WeighCoins = $LeftWeighContainer/LeftWeighCoins
@onready var right_weigh_coins: WeighCoins = $RightWeighContainer/RightWeighCoins
@onready var weigh_result: Label  = $WeighResult
const COLOR_OVERLAY: PackedScene  = preload("res://core/components/color_overlay.tscn")



var coin_selected: Array[bool]    = [false, false, false, false, false, false, false, false, false, false, false, false]
var coin_value: Array[int]        = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
var left_coins: Array[int]        = []
var left_coins_index: Array[int]  = []
var right_coins: Array[int]       = []
var right_coins_index: Array[int] = []
var left_count: int               = 3
var history: Array                = []
var matrix: Array[Variant]        = [[0, 1, 1], [1, 0, 1], [-1, -1, 0], [0, 1, -1], [1, 0, -1], [1, -1, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [-1, -1, 1], [-1, 1, -1], [-1, -1, -1]]
var matrix2: Array[Variant]       = [[0, 1, 1], [-1, 0, -1], [1, 1, 0], [0, 1, -1], [1, 0, -1], [1, -1, 0], [0, 0, 1], [0, 1, 0], [-1, 0, 0], [-1, -1, 1], [1, -1, 1], [-1, -1, -1]]
var current_count: int            = 0
var matrix_chosen: Array[Variant] = []


func _shuffle_matrix() -> void:
	matrix.shuffle()
	matrix2.shuffle()


func _chose_random_matrix() -> Array[Variant]:
	if randi_range(0, 1) == 0:
		return matrix
	else:
		return matrix2


func _ready() -> void:
	_restart_game()
	_show_puzzle_info()


func _restart_game() -> void:
	first.hide()
	second.hide()
	third.hide()
	weigh_result.text = " "
	animation_player.play("RESET")
	left_weigh_coins.clear_coins()
	right_weigh_coins.clear_coins()
	_reset_coins(false)
	_shuffle_matrix()
	_generate_history()
	first.show()
	second.show()
	third.show()


func _generate_history() -> void:
	matrix_chosen = _chose_random_matrix()
	history.clear()
	history = [
		{
			"left_coins": [],
			"right_coins": [],
			"left_weight": 0,
			"right_weight": 0,
			"left_coins_index": [],
			"right_coins_index": []
		},
		{
			"left_coins": [],
			"right_coins": [],
			"left_weight": 0,
			"right_weight": 0,
			"left_coins_index": [],
			"right_coins_index": []
		},
		{
			"left_coins": [],
			"right_coins": [],
			"left_weight": 0,
			"right_weight": 0,
			"left_coins_index": [],
			"right_coins_index": []
		},
	]
	for i in range(len(matrix_chosen)):
		if matrix_chosen[i][0] > 0:
			history[0]["left_coins"].append(1)
			history[0]["left_coins_index"].append(i)
		elif matrix_chosen[i][0] < 0:
			history[0]["right_coins"].append(1)
			history[0]["right_coins_index"].append(i)
		if matrix_chosen[i][1] > 0:
			history[1]["left_coins"].append(1)
			history[1]["left_coins_index"].append(i)
		elif matrix_chosen[i][1] < 0:
			history[1]["right_coins"].append(1)
			history[1]["right_coins_index"].append(i)
		if matrix_chosen[i][2] > 0:
			history[2]["left_coins"].append(1)
			history[2]["left_coins_index"].append(i)
		elif matrix_chosen[i][2] < 0:
			history[2]["right_coins"].append(1)
			history[2]["right_coins_index"].append(i)


func _show_histroy(index: int) -> void:
	current_count = index
	_reset_coins(false)
	left_weigh_coins.clear_coins()
	right_weigh_coins.clear_coins()

	var hist         = history[index]
	var _left_index  = hist.get("left_coins_index")
	var _right_index = hist.get("right_coins_index")
	for l_i in _left_index:
		# 偏绿
		coins[l_i].modulate = Color(0.2, 0.8, 0.2, 0.5)
		left_weigh_coins.add_coins(1, Color(0.2, 0.8, 0.2))

	for r_i in _right_index:
		# 偏红
		coins[r_i].modulate = Color(0.8, 0.2, 0.2, 0.5)
		right_weigh_coins.add_coins(1, Color(0.8, 0.2, 0.2))

	var _left_weight  = hist.get("left_weight")
	var _right_weight = hist.get("right_weight")
	if _left_weight > _right_weight:
		# 切换到left动画, 并停留在第1.1秒
		animation_player.play("left")
		animation_player.seek(1.1, true)  # 跳转到第1秒
		animation_player.pause()

	elif _right_weight > _left_weight:
		# 切换到right动画, 并停留在第1.1秒
		animation_player.play("right")
		animation_player.seek(1.1, true)  # 跳转到第1秒
		animation_player.pause()

	else:
		# 切换到idle动画, 并停留在第0.5秒
		animation_player.play("idle")
		animation_player.seek(0.5, true)
		animation_player.pause()


func _reset_coins(activate: bool = true):
	for i in range(coins.size()):
		if activate:
			coins[i].activate()
		else:
			coins[i].deactivate()
		coins[i].button_pressed = false
		coins[i].modulate = Color.WHITE


func _on_first_pressed() -> void:
	_show_histroy(0)


func _on_second_pressed() -> void:
	_show_histroy(1)


func _on_third_pressed() -> void:
	_show_histroy(2)


func _on_left_heavier_pressed() -> void:
	history[current_count]["left_weight"] = 1
	history[current_count]["right_weight"] = 0
	_show_histroy(current_count)


func _on_balance_pressed() -> void:
	history[current_count]["left_weight"] = 0
	history[current_count]["right_weight"] = 0
	_show_histroy(current_count)


func _on_right_heavier_pressed() -> void:
	history[current_count]["left_weight"] = 0
	history[current_count]["right_weight"] = 1
	_show_histroy(current_count)


func _on_restart_game_pressed() -> void:
	_restart_game()


func _on_puzzle_info_pressed() -> void:
	_show_puzzle_info()


func _on_back_to_menu_pressed() -> void:
	GameManager.back_to_main_menu()


func _show_puzzle_info() -> void:
	var overlay: ColorOverlay = COLOR_OVERLAY.instantiate()

	add_child(overlay)

	overlay.set_title(tr("fc.fake_coin_puzzle"))
	overlay.set_label(tr("fc.fake_coin_quizmaster_puzzle_info"))
	var confirm_button: Button = Button.new()
	confirm_button.text = tr("m.confirm")
	confirm_button.connect("pressed", overlay.queue_free)

	overlay.operation_container.add_child(confirm_button)


func _on_confirm_weigh_result_pressed() -> void:
	_find_result()


func _find_result() -> void:
	var result_list: Array[int]     = []
	var opp_result_list: Array[int] = []
	for i in history:
		result_list.append(i.get("left_weight") + i.get("right_weight") * -1)
		opp_result_list.append(i.get("right_weight") + i.get("left_weight") * -1)

	var find_result: int     = matrix_chosen.find(result_list)
	var find_opp_result: int = matrix_chosen.find(opp_result_list)
	if find_result >= 0:
		weigh_result.text = tr("fc.th_pre") + str(find_result + 1) + tr("fc.th_coin") + " " + tr("fc.heavier")
	elif find_opp_result >= 0:
		weigh_result.text = tr("fc.th_pre") + str(find_opp_result + 1) + tr("fc.th_coin") + " " + tr("fc.lighter")
	else:
		weigh_result.text = tr("fc.no_fake_coin")



func _on_contestant_mode_pressed() -> void:
	get_tree().change_scene_to_file("res://core/puzzles/fake_coin/contestant‌.tscn")
